package com.icefish.daoImpl;

import com.icefish.bean.Good;
import com.icefish.dao.GoodDao;
import com.icefish.utils.DatabaseConnFactory;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class GoodDaoImpl implements GoodDao {

    //查询所有商品信息
    @Override
    public List<Good> selectGoodList() throws SQLException {
        String sql="select * from goods";
        Connection conn = DatabaseConnFactory.getConn();

        Statement statement = conn.createStatement();
        ResultSet rst = statement.executeQuery(sql);


        // 遍历rst，从中获取到查询的数据
        List<Good> GoodList = new ArrayList<>();

        while(rst.next()){

            //获取当前行的每列数据，根据列名获取
            int goods_id = (int) rst.getObject("goods_id");
            String goods_name = (String) rst.getObject("goods_name");
            Integer goods_price=(Integer) rst.getObject("goods_price");
            String  goods_picture=(String) rst.getObject("goods_picture");
            String  goods_describe=(String) rst.getObject("goods_describe");

            //将查询到的数据封装到Good对象
            Good good = new Good(goods_id,goods_name,goods_price,goods_picture,goods_describe);

            GoodList.add(good);

        }
        rst.close();
        return GoodList;
    }

    //根据商品Id获取商品信息
    @Override
    public Good selectGoodByGoodId(Integer id) throws SQLException {

        String sql = "select * from goods where goods_id=?";
        Connection conn = DatabaseConnFactory.getConn();

        PreparedStatement psmt = conn.prepareStatement(sql);
        psmt.setInt(1, id);
        ResultSet rst = psmt.executeQuery();

        Good good = new Good();
        while(rst.next()){

            good.setGoods_id(rst.getInt("goods_id"));
            good.setGoods_name(rst.getString("goods_name"));
            good.setGoods_price(rst.getInt("goods_price"));
            good.setGoods_picture(rst.getString("goods_picture"));
            good.setGoods_describe(rst.getString("goods_describe"));

        }
        rst.close();
        return good;
    }
}
